#!/usr/bin/env node

const WebSocket = require('ws');

// 测试线上WebSocket连接
async function testOnlineWebSocket() {
  console.log('开始测试线上WebSocket连接...');
  
  const wsUrl = 'wss://c4pad.fun/socket.io/?EIO=4&transport=websocket';
  console.log('连接URL:', wsUrl);
  
  try {
    const ws = new WebSocket(wsUrl);
    
    ws.on('open', function open() {
      console.log('✅ WebSocket连接成功');
      
      // 发送Socket.IO握手消息
      console.log('发送Socket.IO握手消息...');
      ws.send('40'); // Socket.IO connect message for default namespace
      
      // 等待2秒后发送加入聊天消息
      setTimeout(() => {
        console.log('发送加入聊天消息...');
        const joinMessage = JSON.stringify(['join_chat', { username: 'TestUser' + Date.now() }]);
        const message = '42' + joinMessage;
        console.log('发送的完整消息:', message);
        ws.send(message); // Socket.IO event message
      }, 2000);
      
      // 等待3秒后发送心跳测试
      setTimeout(() => {
        console.log('发送心跳测试...');
        ws.send('2'); // Socket.IO ping
      }, 3000);
      
      // 等待4秒后尝试发送其他测试消息
      setTimeout(() => {
        console.log('发送连接测试消息...');
        const testMessage = JSON.stringify(['test_connection', { message: 'hello' }]);
        ws.send('42' + testMessage);
      }, 4000);
      
      // 8秒后关闭连接
      setTimeout(() => {
        console.log('关闭连接...');
        ws.close();
      }, 8000);
    });
    
    ws.on('message', function message(data) {
      console.log('📨 收到消息:', data.toString());
      
      // 解析Socket.IO消息
      const dataStr = data.toString();
      if (dataStr.startsWith('42')) {
        try {
          const eventData = JSON.parse(dataStr.substring(2));
          console.log('   事件类型:', eventData[0]);
          console.log('   事件数据:', JSON.stringify(eventData[1], null, 2));
        } catch (e) {
          console.log('   无法解析事件数据');
        }
      } else if (dataStr.startsWith('40')) {
        console.log('   Socket.IO连接确认');
      } else if (dataStr.startsWith('3')) {
        console.log('   心跳消息');
      }
    });
    
    ws.on('error', function error(err) {
      console.error('❌ WebSocket错误:', err.message);
    });
    
    ws.on('close', function close(code, reason) {
      console.log('🔌 WebSocket连接关闭');
      console.log('   关闭代码:', code);
      console.log('   关闭原因:', reason ? reason.toString() : '无');
    });
    
  } catch (error) {
    console.error('❌ 连接失败:', error.message);
  }
}

// 测试普通HTTP连接
async function testHttpConnection() {
  console.log('\n测试HTTP连接...');
  
  try {
    const https = require('https');
    
    const options = {
      hostname: 'c4pad.fun',
      port: 443,
      path: '/socket.io/?EIO=4&transport=polling',
      method: 'GET',
    };
    
    const req = https.request(options, (res) => {
      console.log('✅ HTTP状态码:', res.statusCode);
      console.log('   响应头:', JSON.stringify(res.headers, null, 2));
      
      let data = '';
      res.on('data', (chunk) => {
        data += chunk;
      });
      
      res.on('end', () => {
        console.log('   响应内容:', data.substring(0, 200) + (data.length > 200 ? '...' : ''));
      });
    });
    
    req.on('error', (err) => {
      console.error('❌ HTTP请求错误:', err.message);
    });
    
    req.end();
    
  } catch (error) {
    console.error('❌ HTTP测试失败:', error.message);
  }
}

// 主函数
async function main() {
  console.log('=== 线上WebSocket连接测试 ===\n');
  
  await testHttpConnection();
  
  setTimeout(() => {
    testOnlineWebSocket();
  }, 2000);
}

main().catch(console.error);
